package xyz.labmem.base.sys.util

import org.slf4j.LoggerFactory

import xyz.labmem.base.sys.util.ip.IpUtils
import com.alibaba.fastjson.JSONObject
import xyz.labmem.base.core.consts.GBK
import xyz.labmem.base.sys.util.http.HttpUtils

class AddressUtils {
    private val log = LoggerFactory.getLogger(AddressUtils::class.java)

    // IP地址查询
    val IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"

    // 未知地址
    val UNKNOWN = "XX XX"

    fun getRealAddressByIP(ip: String): String? {
        val address = UNKNOWN
        // 内网不查询
        if (IpUtils().internalIp(ip)) {
            return "内网IP"
        }
        try {
            val rspStr: String? = HttpUtils().sendGet(IP_URL, "ip=$ip&json=true", GBK)
            if (rspStr?.let { StringUtils().isEmpty(it) } == true) {
                log.error("获取地理位置异常 {}", ip)
                return UNKNOWN
            }
            val obj: JSONObject = JSONObject.parseObject(rspStr)
            val region: String = obj.getString("pro")
            val city: String = obj.getString("city")
            return String.format("%s %s", region, city)
        } catch (e: Exception) {
            log.error("获取地理位置异常 {}", ip)
        }
        return address
    }
}